import { ref, reactive, computed } from "vue";
import { useRouter } from "vue-router";
import { clone } from "@pureadmin/utils";
import dayjs from "dayjs";
import { utils, writeFile } from "xlsx";
import { message } from "@/utils/message";
import type { FormInstance, FormRules, UploadProps, UploadUserFile, } from 'element-plus'

import { seldictionarybypage } from '@/api/dictionaries'
import { useUserStoreHook } from "@/store/modules/user";
import { ElMessageBox } from 'element-plus'




export function usepageTable(query) {
  const router = useRouter();

  const params = clone(query, true);
  const currentPage = ref(params?.tableInit?.paginationConfig?.currentPage);
  const pageSize = ref(params?.tableInit?.paginationConfig?.pageSize);
  const total = ref(0);

  // const date = dayjs(new Date()).format("YYYY-MM-DD");

  const tableData = ref([]);

  const loading = ref(false);
  // 增
  const addData = (form) => {
    params.addRes(form).then(res => {
      getData()
      DrawerRef.value?.close();
      DialogRef.value?.close();
      message("创建成功", {
        type: "success"
      });
    })
  };

  // 删
  const delData = (userid) => {
    params.delRes(userid).then(res => {
      getData()
      DrawerRef.value?.close();
      message("删除成功", {
        type: "success"
      });
    })
  };
  // 改
  const amendData = (form) => {
    let query = clone(form, true)
    params.updateRes(query).then(res => {
      if (params.updateResCallBack && typeof params.updateResCallBack === 'function') {
        params.updateResCallBack()
        return
      }
      getData()
      DrawerRef.value?.close();
      DialogRef.value?.close();

      message("修改成功", {
        type: "success"
      });
    })
  };
  // 查
  const getData = () => {
    loading.value = true;
    let reqParams = {
      size: pageSize.value,
      index: currentPage.value,
      ...serachVal.value,
      ...params.otherQuery
    };
    params
      .getRes(reqParams)
      .then(res => {
        tableData.value = res.result;
        total.value = res.total;
        params.tableInit.total = res.page?.total ?? 0;
      })
      .finally(() => {
        loading.value = false;
      });
  };

  // 搜索

  const serachVal = ref(null);
  const searchSubmit = (e: any): void => {
    serachVal.value = e;
    getData();
  };

  // 分页
  const sizeChange = e => {
    currentPage.value = 1;
    pageSize.value = e;
    getData();
  };

  const currentChange = e => {
    currentPage.value = e;
    getData();
  };

  // 导出

  const exportExcel = () => {
    const noExportList = ["operation"];

    const tableDataDrag = clone(tableData.value, true).map((item, index) => {
      // delete item["address"];
      // delete item["operation"];
      // delete item["date"];
      return Object.assign(
        {
          id: index + 1,
          date: `${dayjs(new Date()).format("YYYY-MM")}-${index + 1}`
        },
        item
      );
    });

    const dataList = ref(clone(tableDataDrag, true));

    const res = dataList.value.map(item => {
      const arr = [];
      params.tableInit.propList.forEach(column => {
        if (!noExportList.includes(column.prop)) {
          arr.push(item[column.prop as string]);
        }
      });
      return arr;
    });
    const titleList = [];
    params.tableInit.propList.forEach(column => {
      if (!noExportList.includes(column.prop)) {
        titleList.push(column.label);
      }
    });
    res.unshift(titleList);
    const workSheet = utils.aoa_to_sheet(res);
    const workBook = utils.book_new();
    utils.book_append_sheet(workBook, workSheet, "数据报表");
    writeFile(workBook, params.xlsxName ? params.xlsxName : "admin-table.xlsx");
    message("导出成功", {
      type: "success"
    });
  };

  const IformConfig = ref(params?.formConfig);


  // 表格
  const ruleFormRef = ref<FormInstance>()


  // 弹框

  const DialogRef = ref(null);
  const openDialog = (text, ruleForm, pageType, row, callback) => {
    if (pageType) {
      getOptionsType(pageType, seldictionarybypage)
    }

    typeText.value = text
    if (row) {
      Object.keys(ruleForm).forEach((key) => {
        if (row[key]) {
          ruleForm[key] = isJSON(row[key])
        }
      })

    }
    if (callback && typeof callback == 'function') callback()
    console.log(ruleForm, 'callback')

    DialogRef.value.open();
    dialogLoading.value = false
  };

  const typeText = ref('')



  const DialogSubmit = (ruleForm, otherParamas) => {
    console.log(otherParamas, 'otherParamas')
    if (!ruleFormRef.value) return
    ruleFormRef.value.validate((valid) => {
      if (valid) {
        let Q = {
          ...ruleForm,
          ...otherParamas
        }
        console.log(Q, 'Q')

        if (typeText.value === '新增') {
          addData(Q)
        } else {
          amendData(Q)
        }
      } else {
        console.log('error submit!')
        return false
      }
    })


  };

  const onDialogClose = (ruleForm) => {
    if (!ruleFormRef.value) return
    console.log(ruleForm)

    ruleFormRef.value.resetFields()
    Object.keys(ruleForm).forEach((key) => {
      if (typeof ruleForm[key] !== 'object') {
        ruleForm[key] = ''
      } else {
        ruleForm[key] = []
      }
    })
    console.log(ruleForm)
  };

  // 侧边栏
  const DrawerType = ref("新增");
  const DrawerRef = ref(null);
  const DrawerLoading = ref(true)
  const optionsDetail = ref(null) // 侧边栏内容详情

  const openDrawer = (id, a, b, row) => {
    DrawerLoading.value = true
    isStopCancelisStopCancelVal.value = a
    isLook.value = b
    if (params?.detailRes && !row) {
      params?.detailRes(id).then(res => {
        optionsDetail.value = res.result
      }).finally(() => DrawerLoading.value = false)
    } else {
      optionsDetail.value = row
      DrawerLoading.value = false
    }
    console.log(optionsDetail.value, 'optionsDetail.value')
    DrawerRef.value.initForm();
    DrawerRef.value.open();
  };



  const DrawerSubmit = () => {
    DrawerLoading.value = true
    console.log('审核通过')
    let Q = {
      id: optionsDetail.value.id,
      shzt: 1  //审核状态 1 通过 2驳回
    }
    params.auditRes(Q).then(() => {
      isStopCancelisStopCancelVal.value = false
      setTimeout(() => {
        DrawerRef.value.close();
      }, 200)
    }).finally(() => {
      DrawerLoading.value = false
    })


  };

  const onDrawerClose = () => {
    getData();

    isStopCancelisStopCancelVal.value = true
    optionsDetail.value = null
  };



  const isStopCancelisStopCancelVal = ref(true) // 控制侧边栏的取消按钮是否冒泡，新功能可删除
  const isLook = ref(true)

  const cancelCloseFn = () => {

    ElMessageBox.prompt('请输入驳回理由', '驳回信息', {
      confirmButtonText: '提交',
      cancelButtonText: '取消',
      // inputErrorMessage: 'Invalid Email',
    })
      .then(({ value }) => {
        isStopCancelisStopCancelVal.value = false

        DrawerLoading.value = true
        let Q = {
          ly: value,
          id: optionsDetail.value.id,
          shzt: 2  //审核状态 1 通过 2驳回
        }
        params.auditRes(Q).then(() => {
          getData();
          setTimeout(() => {
            DrawerRef.value.close()
          }, 200)
        }).finally(() => {
          DrawerLoading.value = false
        })
      })
      .catch(() => {

      })
  }



  // 过滤函数
  // 0 待付款 1 已完成 2 待收货 3 退货 4 待发货 5退货完成
  const filterOrder = orderstatu => {
    const type = Number(orderstatu);
    let text;
    switch (type) {
      case 0:
        text = "待付款";
        break;
      case 1:
        text = "已完成";
        break;
      case 2:
        text = "待收货";
        break;
      case 3:
        text = "退货中";
        break;
      case 4:
        text = "待发货";
        break;
      case 5:
        text = "退货完成";
        break;
    }
    return text;
  };

  const filterColor = orderstatu => {
    if (!orderstatu) return ''
    const type = Number(orderstatu);
    let text;
    switch (type) {
      case 0:
        text = "primary";
        break;
      case 1:
        text = "info";
        break;
      case 2:
        text = "success";
        break;
      case 3:
        text = "danger";
        break;
      case 4:
        text = "";
        break;
      case 5:
        text = "warning";
        break;
    }
    return text;
  };


  const filterStatus = status => {
    const type = Number(status);
    let text;
    switch (type) {
      case 0:
        text = "停止供货";
        break;
      case 1:
        text = "正在供货";
        break;
      case 2:
        text = "预发布";
        break;
    }
    return text;
  };

  const productStatus = [
    { name: '停止供货', id: 0 },
    { name: '正在供货', id: 1 },
    { name: '预发布', id: 2 },
  ]

  // 文档权限
  const filesStatus = [
    { name: '所有人可看', id: 0 },
    { name: '需要登陆', id: 1 },
    { name: '需申请', id: 2 },
  ]

  const filterStatusName = (status) => {
    const type = Number(status);
    let text;
    switch (type) {
      case 0:
        text = "所有人可看";
        break;
      case 1:
        text = "需要登陆";
        break;
      case 2:
        text = "需申请";
        break;
    }
    return text;
  }

  const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
    number = (number + "").replace(/[^0-9+-Ee.]/g, "");
    const n = !isFinite(+number) ? 0 : +number;
    const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals);
    const sep = typeof thousands_sep === "undefined" ? "," : thousands_sep;
    const dec = typeof dec_point === "undefined" ? "." : dec_point;
    let s = "";
    const toFixedFix = function (n, prec) {
      const k = Math.pow(10, prec);
      return "" + Math.ceil(n * k) / k;
    };
    s = (prec ? toFixedFix(n, prec) : "" + Math.round(n)).split(".");
    const re = /(-?\d+)(\d{3})/;
    while (re.test(s[0])) {
      s[0] = s[0].replace(re, "$1" + sep + "$2");
    }

    if ((s[1] || "").length < prec) {
      s[1] = s[1] || "";
      s[1] += new Array(prec - s[1].length + 1).join("0");
    }
    return s.join(dec);
  };


  const formatPhone = (str, sign = '-') => str.replace(/(\W|\s)/g, "").split(/^(\d{3})(\d{4})(\d{4})$/).filter(item => item).join(sign)


  // 图片JSON自动转成object
  const isJSON = (variable) => {
    if (typeof variable !== 'string') {
      return variable
    }

    let json

    try {
      json = JSON.parse(variable)
    } catch (error) {
      return variable
    }


    console.log(typeof json, 'typeof json')
    console.log(json)
    if (typeof json !== 'object') {
      return variable
    }
    return json
  }

  // 图片object自动转成JSON
  const toJSON = (variable) => {
    if (typeof variable !== 'object') {
      return variable
    }

    let json

    try {
      json = JSON.stringify(variable)
    } catch (error) {
      return variable
    }
    return json
  }






  // 获取xx分类列表

  const classifyOptions = computed(() => useUserStoreHook().classifyOptions)
  interface optionsType {
    label?: string
    value?: any
  }
  const options = ref<optionsType[]>([])
  const dialogLoading = ref(true)
  const getOptionsType = (typeText, api) => {
    dialogLoading.value = true
    let item = classifyOptions.value.find((v) => v.label == typeText)
    if (item) {
      api({ sslb: item.value, index: 1, size: 100 }).then(res => {
        options.value = res.result.map(v => {
          return {
            label: v.name,
            value: v.id
          }
        })
      }).finally(() => {
        dialogLoading.value = false
      })
    } else {
      setTimeout(() => {
        getOptionsType(typeText, api)
      }, 500)
    }
  }







  return {
    getData,
    addData,
    amendData,
    delData,
    tableData,
    loading,
    exportExcel,
    params,
    sizeChange,
    currentChange,
    currentPage,
    pageSize,
    searchSubmit,
    serachVal,


    typeText,

    DialogRef,
    openDialog,
    DialogSubmit,
    onDialogClose,


    DrawerRef,
    openDrawer,
    DrawerSubmit,
    onDrawerClose,
    DrawerType,
    IformConfig,
    DrawerLoading,  // 侧边栏loading
    optionsDetail, // 侧边栏详情
    cancelCloseFn,
    isLook,
    isStopCancelisStopCancelVal,





    filterOrder,
    moneyFormat,
    filterColor,
    formatPhone,
    filterStatus,
    productStatus,
    filesStatus,
    filterStatusName,
    isJSON,
    toJSON,


    dialogLoading,
    getOptionsType,
    options,
    ruleFormRef,



    classifyOptions



  };
}
